#include <stdio.h>
#include "cmsis_os2.h"
#include "ohos_run.h"

#include "driver/uart.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
#include "esp_log.h"

#define TASK_STACK_SIZE 4096
#define TASK_PRIO 25

osThreadId_t g_taskID = NULL;

#define ECHO_UART_PORT_NUM (UART_NUM_0)
#define ECHO_UART_BAUD_RATE (115200)

#define BUF_SIZE (1024)

static void uart_test(void)
{
    /* Configure parameters of an UART driver,
     * communication pins and install the driver */
    uart_config_t uart_config = {
        .baud_rate = ECHO_UART_BAUD_RATE,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
    };

    ESP_ERROR_CHECK(uart_param_config(ECHO_UART_PORT_NUM, &uart_config));
    ESP_ERROR_CHECK(uart_driver_install(ECHO_UART_PORT_NUM, BUF_SIZE, BUF_SIZE, 0, NULL, 0));

    // Configure a temporary buffer for the incoming data
    uint8_t *data = (uint8_t *)malloc(BUF_SIZE);

    // Write data back to the UART
    uart_write_bytes(ECHO_UART_PORT_NUM, "uart is ok!\r\n", strlen("uart is ok!\r\n"));

    while (1)
    {
        // Read data from the UART
        int len = uart_read_bytes(ECHO_UART_PORT_NUM, data, (BUF_SIZE - 1), 20 / portTICK_PERIOD_MS);

        if (len)
        {
            data[len] = '\0';
            printf("recv: %s", (char *)data);
        }
    }
}

static void uart_example_task(void)
{
    printf("into uart hdf example!\n");
    osThreadAttr_t attr;
    attr.name = "uart_test";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;
    g_taskID = osThreadNew((osThreadFunc_t)uart_test, NULL, &attr);
    if (g_taskID == NULL)
    {
        printf("Failed to create Test Uart thread!\n");
    }
}

OHOS_APP_RUN(uart_example_task);
